package naga.x.platform2.channel.j9kgames.support;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.utils.CommonUtils;
import naga.x.platform2.utils.UUID;

/**
 * 游戏金榜
 * @see <a href="https://dev.99kgames.com/gameApi/index/partnerid/aad2ac3ebbccd039ea8600d20b9feea8">游戏金榜技术对接-万家</a>
 * @author yang.li
 *
 */
@Component
public class J9KGamesApi {
	
	@Autowired
	private J9KGamesConfig config;
	
	public static final String HOST = "http://api.99kgames.com";
	public static final String URL_GET_USER = HOST + "/vendor/api/userinfo";
	public static final String URL_SUBSCRIBE = HOST + "/vendor/api/subscribe";
	
	public String makeSign(Map<String, String> params) {
		Map<String, String> tree = params instanceof TreeMap ? params : new TreeMap<String, String>(params);
		Set<Entry<String, String>> set = tree.entrySet();
		StringBuilder buf = new StringBuilder(128);
		for (Entry<String, String> entry : set) {
			String key = entry.getKey();
			String val = entry.getValue();
			buf.append(key).append('=').append(val != null ? val : "").append('&');
		}
		buf.setLength(buf.length() - 1); // remove the last '&'
		buf.append(config.getSecKey());
		return CommonUtils.encryptToHexString("SHA-1", buf.toString());
	}
	
	public Object makeOrderErrorResponse(String msg) {
		JSONObject res = new JSONObject(2);
		res.put("out_trade_no", "-1");
		res.put("msg", msg);
		return res;
	}
	
	public Object makeOrderResponse(RechargeTemplate template, Integer sid, Long pid) {
		Map<String, String> res = new TreeMap<>();
		// 我方订单号
		res.put("out_trade_no", UUID.randomUUID().toString());
		// 商品id
		res.put("product_id", String.valueOf(template.getId()));
		// 支付金额（分）
		res.put("total_fee", String.valueOf(template.getPrice() * 100));
		// 商品名
		res.put("body", template.getName());
		// 商品详情
		res.put("detail", template.getDesc());
		// 附加数据
		res.put("attach", sid + "|" + pid);
		// 签名
		res.put("sign", makeSign(res));
		return res;
	}

}
